package com.carlinfo.userscenter.common.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 标准的JDBC
 * 
 * @author JayLong
 *
 */
public class DbUtil
{
	public static void main(String[] args)
	{
		String driver = "com.mysql.jdbc.Driver";
		String url = "jdbc:mysql://localhost:3306/userscenter_20180108?useSSL=true";
		String user = "root";
		String password = "123456";
		String sql = "select * from a_role;";
		/* 为对象赋初始值 */
		Connection connection = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try
		{
			/* 加载驱动 */
			Class.forName(driver);
			/* 获取链接 */
			connection = DriverManager.getConnection(url, user, password);
			/* 操作数据库
			 * Statement:没有预先加载
			 * preparedStatement:预先加载
			 * */
			ps = connection.prepareStatement(sql);
			rs = ps.executeQuery();
			/* 到底是循环还是选择
			 * 如果查询的结果是多条,就用判断
			 * 如果查询的是单条,就用选择
			 * */
			while(rs.next())
			{
				/* 
				 * 参数为整数:指的是sql语句执行以后;列的顺序
				 * 参数为字符串时:指的是sql语句执行以后列的别名;
				 * */
				int id = rs.getInt(1);
				String name = rs.getString("name");
				System.out.println("id:" + id  + ";name" + name);
			}
		} catch (ClassNotFoundException e)
		{
			System.out.println("=====加载驱动失败=====");
			e.printStackTrace();
		} catch (SQLException e)
		{
			System.out.println("=====获取链接失败=====");
			e.printStackTrace();
		}
	}
}
